Telegram Group & Telegram Channel
🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6561
Create:
Last Update:

🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6561

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

What is Telegram Possible Future Strategies?

Cryptoassets enthusiasts use this application for their trade activities, and they may make donations for this cause.If somehow Telegram do run out of money to sustain themselves they will probably introduce some features that will not hinder the rudimentary principle of Telegram but provide users with enhanced and enriched experience. This could be similar to features where characters can be customized in a game which directly do not affect the in-game strategies but add to the experience.

How to Buy Bitcoin?

Most people buy Bitcoin via exchanges, such as Coinbase. Exchanges allow you to buy, sell and hold cryptocurrency, and setting up an account is similar to opening a brokerage account—you’ll need to verify your identity and provide some kind of funding source, such as a bank account or debit card. Major exchanges include Coinbase, Kraken, and Gemini. You can also buy Bitcoin at a broker like Robinhood. Regardless of where you buy your Bitcoin, you’ll need a digital wallet in which to store it. This might be what’s called a hot wallet or a cold wallet. A hot wallet (also called an online wallet) is stored by an exchange or a provider in the cloud. Providers of online wallets include Exodus, Electrum and Mycelium. A cold wallet (or mobile wallet) is an offline device used to store Bitcoin and is not connected to the Internet. Some mobile wallet options include Trezor and Ledger.

Библиотека джависта | Java Spring Maven Hibernate from in


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA